Cuestionario Ampliado del Censo de Población y Vivienda 2020

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Personas_Censo 2020.SAV")
save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

Posibles variables que se pueden contemplar en la movilidad estudiantil

  • SEXO
  • NIVACAD ¿Cuál fue el último año o grado aprobado por (NOMBRE) en la escuela?
  • TIE_TRASLADO_ESCU
  • MED_TRASLADO_ESC1
  • MED_TRASLADO_ESC2
  • MED_TRASLADO_ESC3
  • NOMCAR_C

La variable mydata contiene 15 015 683 observaciones y 27 variables.

load(paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

mydata <- data %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, 
                  EDAD, SEXO, AFRODES,  HLENGUA, QDIALECT_INALI, ELENGUA, PERTE_INDIGENA, ALFABET, ASISTEN, NIVACAD, 
                  ESCOLARI, ESCOACUM,  NOMCAR_C, TIE_TRASLADO_ESCU, MED_TRASLADO_ESC1, MED_TRASLADO_ESC2, MED_TRASLADO_ESC3,  
                  FACTOR, ESTRATO, UPM)

save(mydata, file = paste0(here::here(), "/Bases/04_Movilidad estudiantil_2020.RData"))

✔️A partir de aquí se pueden correr los códidos 👇.
Se carga el archivo Movilidad estudiantil_2020.RData.

load(file = paste0(here::here(), "/Bases/04_Movilidad estudiantil_2020.RData"))

#Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, EDAD, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1)  %>%
             mutate(NOM_ENT = as.factor(.$CVE_ENT)) %>%
              ungroup()

Entidades

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)

nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")

est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2020.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()

# Se le asignan las etiquetas a los nombres de los estados 
levels(mydata$NOM_ENT) <- estados

Población estudiantil de 3 años y más

Se identifica a la población estudiantil de 3 años y más.

filter(EDAD >= 3 & EDAD <= 130)'.

Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <= 130) %>%
                 filter(ENT_PAIS_ASI %in% estados)  # Filtro del lugar de trabajo dentro del país. 

Población de 3 años y más

Nivel estatal

Movilidad estudiantil

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
       as.data.frame() %>%
        mutate(EDAD = as.numeric(.$EDAD)) %>%
         subset(EDAD >= 3 & EDAD <= 130) %>%  
          filter(ENT_PAIS_ASI %in% estados) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/MC_estado.RDS"))

Se genera una matriz cruzada de movilidad estudiantil a nivel estatal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/MC_estado.RDS"))

Migrantes <- svytable(~ENT_PAIS_ASI + CVE_ENT, design = MC) 

La función cross_cases() de la paquetería expss se utiliza para crear tablas de contingencia cruzadas a partir de dos o más variables categóricas. Utilizando el comando weight, permite ponderar las observaciones “factores de expansión” en la tabla.

Se quita la diagonal a la matriz cruadrada con la función diag.remove() de la paquetería sna, donde esta función reemplaza los elementos de la diagonal principal de una matriz por un valor nulo o por el valor especifico.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ENT, ENT_PAIS_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 slice(-33) %>% 
                  select(-row_labels) 

rownames(Migrantes)<- nom_estados
colnames(Migrantes) <- nom_estados

save(Migrantes, file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))
 
wb <- createWorkbook()
addWorksheet(wb, "MEstudiantil 2020")
writeData(wb, 1, Migrantes, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.xlsx"), overwrite = TRUE)

Matriz de movilidad estudiantil a nivel estatal, 2020

Matriz de movilidad estudiantil, 2020
Nivel estatal
Entidad Aguascalientes Baja California Baja California Sur Campeche Coahuila de Zaragoza Colima Chiapas Chihuahua Ciudad de México Durango Guanajuato Guerrero Hidalgo Jalisco México Michoacán de Ocampo Morelos Nayarit Nuevo León Oaxaca Puebla Querétaro Quintana Roo San Luis Potosí Sinaloa Sonora Tabasco Tamaulipas Tlaxcala Veracruz de Ignacio de la Llave Yucatán Zacatecas
Aguascalientes 409195 0 0 0 5 4 0 0 88 0 224 62 0 293 77 0 0 0 59 0 4 20 0 0 12 0 0 0 0 0 59 486
Baja California 0 928737 0 0 0 0 0 106 458 0 79 0 0 165 111 23 0 84 0 0 65 13 0 0 158 532 0 0 0 0 0 0
Baja California Sur 8 389 206978 0 0 0 29 0 118 21 0 23 0 199 47 69 0 0 95 0 0 0 0 0 48 0 0 0 0 21 0 0
Campeche 0 0 8 244610 0 0 158 0 157 0 20 0 0 0 60 0 3 0 143 0 0 0 327 0 0 0 658 41 0 68 1049 0
Coahuila de Zaragoza 0 62 0 0 795408 2 0 64 84 2603 74 0 0 12 93 0 0 0 1856 47 38 5 0 0 46 0 0 48 0 17 0 76
Colima 0 24 0 0 0 188763 0 2 200 0 24 0 0 1093 27 67 0 66 0 0 77 0 0 0 0 0 0 33 0 27 0 0
Chiapas 16 21 0 85 131 10 1515892 5 362 0 4 56 5 149 742 50 10 44 97 195 232 24 10 2 52 9 3680 9 0 153 162 19
Chihuahua 0 0 0 0 64 0 9 980103 168 31 1 0 0 155 12 0 0 2 199 0 12 108 0 7 177 61 0 5 253 2 0 0
Ciudad de México 0 67 33 0 0 0 20 37 2106242 29 0 60 486 239 67109 74 964 21 78 121 1208 252 40 59 42 72 0 58 312 298 100 0
Durango 90 4 4 0 6787 1 0 275 60 499785 65 0 0 27 102 56 0 81 120 0 8 0 0 0 344 4 0 6 0 14 42 177
Guanajuato 47 3 0 0 71 0 0 14 861 28 1570500 10 70 662 424 3586 31 29 289 648 125 7233 8 641 0 36 0 3 11 15 0 46
Guerrero 13 17 19 0 12 11 10 3 1335 12 65 997396 21 204 2251 1435 2209 0 93 277 1783 166 45 7 59 18 14 4 11 37 0 0
Hidalgo 13 26 2 6 108 9 10 39 5899 5 144 11 827461 326 9710 58 47 0 255 81 1968 1930 25 537 0 0 0 92 977 747 17 26
Jalisco 1743 38 75 176 4 1976 255 7 801 247 1020 17 104 2141496 146 1025 5 1173 40 5876 49 35 32 121 90 92 33 47 0 14 37 860
México 12 5 19 0 31 17 44 77 331104 0 166 353 11179 542 4078161 773 1090 9 198 416 9311 2105 217 238 65 6 23 6 425 448 114 20
Michoacán de Ocampo 56 16 0 0 28 441 8 52 548 3 3030 511 11 4040 3012 1183800 6 38 4 35 75 703 18 22 8 0 0 25 0 32 5 11
Morelos 46 2 0 0 153 0 806 0 4862 0 44 126 47 22 1720 66 488434 3 17 1103 5976 77 3 9 3 0 3 7 62 6 3 0
Nayarit 0 7 2 0 5 0 173 0 75 22 62 120 0 3651 301 16 0 337538 14 184 10 9 6 0 298 121 0 0 0 0 0 5
Nuevo León 0 0 0 90 417 0 151 64 472 96 10 0 18 95 92 0 21 27 1415469 5 210 594 0 8806 7 0 53 345 6 81 0 68
Oaxaca 9 51 6 19 74 7 868 184 1372 53 76 1541 62 355 1236 64 53 28 136 1088162 3878 68 37 31 190 45 41 16 27 4433 36 53
Puebla 0 10 2 0 62 12 6 29 2431 12 46 84 802 601 1503 121 1037 0 89 570 1804663 83 233 17 103 31 0 14 3100 1852 6 0
Querétaro 0 0 7 0 9 4 0 0 1085 20 1212 46 379 226 773 115 150 28 137 0 112 608969 0 368 44 2 0 90 0 40 17 10
Quintana Roo 4 0 0 105 98 0 74 0 57 0 5 0 5 62 23 0 10 0 40 0 32 189 455126 0 0 0 155 0 0 32 1465 0
San Luis Potosí 54 0 0 4 32 0 14 12 423 0 58 0 409 163 178 23 0 3 828 33 1465 288 0 751992 8 0 0 1024 23 504 0 742
Sinaloa 27 47 41 0 0 0 0 32 142 72 0 55 0 389 55 0 0 200 282 0 0 83 6 0 814325 546 0 37 0 124 0 0
Sonora 18 653 26 0 5 0 6 59 491 9 0 0 66 72 192 0 0 1 146 0 42 20 0 0 567 742324 0 3 0 18 0 7
Tabasco 0 0 0 202 4 0 1663 0 184 0 0 0 5 6 40 7 0 4 161 573 126 0 30 0 0 7 681447 8 0 552 260 35
Tamaulipas 0 0 0 16 45 0 3 8 80 0 35 0 0 20 12 0 40 0 1535 0 1612 0 15 219 0 34 0 871278 29 500 0 0
Tlaxcala 0 0 0 7 29 16 10 0 994 16 74 16 716 226 826 27 22 0 35 51 18464 48 0 13 20 20 0 0 335194 140 0 0
Veracruz de Ignacio de la Llave 30 36 3 70 17 0 214 35 4450 5 107 172 3271 183 876 87 11 0 407 2188 9090 65 73 235 16 3 803 7783 89 1957584 107 10
Yucatán 0 0 0 461 9 0 4 0 740 0 93 17 0 21 14 0 0 0 1 0 90 112 435 0 0 0 13 10 0 12 608838 4
Zacatecas 2953 2 0 0 355 0 0 33 165 486 201 0 26 1009 141 19 141 50 221 0 26 20 21 427 16 23 0 16 0 4 0 447515
Fuente: Estimaciones del CONAPO.

Gráfico dinámico

Gráfico dinámico de movilidad estudiantil a nivel estatal.

load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

names <- c("Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila", "Colima", 
           "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",    
           "México", "Michoacán", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
           "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
           "Veracruz", "Yucatán", "Zacatecas")

# Paleta de colores
paleta <- rev(colorRampPalette(pals::kovesi.linear_bmy_10_95_c71(100))(32))

p <- chorddiag(tabla, 
               groupNames = names,
               groupColors = paleta, 
               groupnamePadding = 10, 
               #height = 700, 
               #width = 700,
               margin = 120,
               groupThickness = 0.07,
               groupPadding = 3,
               groupnameFontsize = 12,
               fadeLevel = '0.1',
               tickInterval = seq(0, 500000, 10000),
               chordedgeColor = "transparent",
               showZeroTooltips = FALSE,
               showTicks = TRUE)

# Ajusta las etiquetas usando JavaScript para modificar su posición
p <- htmlwidgets::onRender(p, '
      function(el, x) {
        d3.selectAll(".group text")
          .attr("text-anchor", "middle")
          .attr("dx", "0")  
          .attr("dy", "0.75em"); 
      }
')

# Crear un contenedor div y aplicar estilos CSS para centrarlo
#p <- tags$div(style = "display: flex; justify-content: center; align-items: center;", p)

p
p %>% 
 mapshot(url = paste0(here::here(),"/images/MEst_2020.html"))
#htmlwidgets::saveWidget(p, paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/MEst a nivel estatal 2020.html"), selfcontained = TRUE)
#webshot(url = paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/MEst a nivel estatal 2020.html"),
 #         file = paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/MEst a nivel estatal 2020.png"),
  #                cliprect = "viewport")

Gráficos

ChordDiagram

load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0)  

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Paleta de colores
#paleta <- colorRampPalette(pals::ocean.matter(100))(50)
paleta <- colorRampPalette(c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla, paleta)
#svglite::svglite(paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/ChordDiagram de MEst a nivel estatal.svg"), width = 20, height = 20)
file = "/Graficos/Estado/04_Movilidad estudiantil/2020/ChordDiagram de MEst a nivel estatal.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.4,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Gráficos por estados

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) 

rownames(tabla) <- stringr::str_wrap(nom_estados, 100)
colnames(tabla) <- stringr::str_wrap(nom_estados, 100)

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) 

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
### Filtro <<<<  filter(value > 0 & rn != estado[x])
#filtro_mig <- sapply(1:32, function(x)
                      #mean(tail(sort(tabla1[[x]]), 5), na.rm = TRUE))
#p <- data.frame(estados = est,
 #             filtro_estados = filtro_mig)
#write.table(p, file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Filtro a nivel estatal.txt"))
#write.xlsx(p, file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Filtro a nivel estatal.xlsx"))

filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Filtro a nivel estatal.xlsx"), colNames = TRUE) %>% 
               pull(filtro_estados)

tabla1 <- migration_flows_states(tabla = tabla, 
                                 filtro_mig = filtro_mig, 
                                 filtro_est = filtro_est, 
                                 category = estado, 
                                 group = "Otro estados")

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
                                 name = "Total",,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Matriz MEst por estados_2020_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Tabla MEst por estados.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Tabla MEst por estados.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_ENT", 
                        Inmigrantes = "Salen por estudio",  
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_ENT", 
                                  Inmigrantes = "%Salen por estudio",  
                                  Emigrantes = "%Entran por estudio")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(),  "/Output/Estado/04_Movilidad estudiantil/2020/Matriz MEst por estados_2020_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Tabla MEst por estados.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- colorRampPalette(c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Estado/04_Movilidad estudiantil/2020/ChordDiagram de MEst para cada estado.pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.2,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Estado/04_Movilidad estudiantil/2020/Etiquetas a nivel estatal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(nom_estados))

Gráfico Sankey

Población estudiantil de 3 años y más

Se genera la variable Pob.3ymas sin ningún filtro y se desagrega a nivel estatal para futuros cálculos.

load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

Migrantes <- Migrantes %>%
              sna::diag.remove(remove.val = 0)  

rownames(Migrantes) <- stringr::str_wrap(nom_estados, 50)
colnames(Migrantes) <- stringr::str_wrap(nom_estados, 50)

# Matiz movilidad interna
tabla <- Migrantes %>% 
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             as_tibble() %>%
              mutate(rn = forcats::fct_relevel(.$rn, nom_estados),
                     cn = forcats::fct_relevel(.$cn, nom_estados)) %>%
               filter(value >= 0)  
p <- tabla %>% 
       ggplot(aes(axis1 = rn, 
                   axis2 = cn, 
                    y = value),  # c("value", "freq", "tasa")
               reverse = FALSE, 
                na.rm = TRUE) +
        geom_alluvium(aes(fill = rn),
                       curve_type = "quintic", 
                        color = "transparent", 
                         alpha = 0.85, 
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
          geom_stratum(aes(fill = cn), 
                        color = "white", 
                         alpha = 0.65,  
                          lwd = 0.001, 
                           width = 1/5,
                            reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.2,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .2, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() + 
              theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 8, family = "montserrat"),
                           legend.position = c(1, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.35)) +
                scale_fill_viridis_d(option = "A") +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/GSankey de MEst a nivel estatal.pdf")
ggexport(p, width = 18, height = 10, dpi = 400, filename = path)

Desagregado por estado

load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

# Se cambian las equiquetas de los estados 
estados <- est 

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

tabla <- Migrantes %>%
          sna::diag.remove(remove.val = 0) %>%
           as.data.frame() %>%
            tibble::rownames_to_column(var = "rn") %>% 
             melt(., id.vars = "rn", variable.name = "cn") %>%
              mutate_if(is.factor, as.character) %>%
               mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% estados | .$cn %in% estados), value, 0)) %>%
                mutate(rn = forcats::fct_relevel(.$rn, estados),
                       cn = forcats::fct_relevel(.$cn, estados)) 
p <- lapply(1:32, function(x){
                   tabla <- tabla %>%
                             mutate(rn = forcats::fct_relevel(.$rn, estados),
                                    cn = forcats::fct_relevel(.$cn, estados)) %>%
                              mutate(value = ifelse(.$rn %in% estados[x] | .$cn %in% estados[x], value, 0)) 
 
                    tabla %>% 
                     ggplot(aes(axis1 = rn, 
                                 axis2 = cn, 
                                  y = value),  # c("value", "freq", "tasa")
                             reverse = FALSE, 
                              na.rm = TRUE) + 
                      geom_alluvium(aes(fill = rn),  
                                     color = "transparent", 
                                      alpha = 0.8, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                       geom_stratum(aes(fill = rn), 
                                     color = "#F1F1F1", 
                                      alpha = 1, 
                                       lwd = 0.001, 
                                        width = 1/5,
                                         reverse = FALSE) +
                         geom_text_repel(aes(label = ifelse(after_stat(x)  == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                             fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = -.2, 
                                               force = 1,
                                                        force_pull = 0,
                                                         family = "montserrat",
                                                          reverse = FALSE) +
                          geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                              fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                           stat = "stratum", 
                                            size = 3,
                                             direction = "y", 
                                              nudge_x = .2, 
                                               force = 1,
                                                force_pull = 0,
                                                 family = "montserrat",
                                                  reverse = FALSE) +
                            theme_void() + 
                             theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                                    text = element_text(family = "montserrat"),
                                     axis.text = element_blank(),
                                      axis.title = element_blank(),
                                       strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                        legend.key.size = unit(0.5, "cm"),
                                         legend.text = element_text(size = 9, family = "montserrat"),
                                          legend.position = c(1, .5)) + 
                              scale_x_discrete(expand = c(-0.1, 0.35)) +
                               scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                                guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                                 labs(fill = "", 
                                      color = "")
              }
)

path = paste0(here::here(), "/Graficos/Estado/04_Movilidad estudiantil/2020/GSankey de MEst desagregado por estados_Absolutos.pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de movilidad:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • \(\%\) Inmigrantes

  • \(\%\) %Emigrante

  • Migración bruta

  • Migración Neta

  • \(\%\) Tasa de movilidad bruta

  • \(\%\) Tasa de movilidad neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ENT) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Pob. estudiantil de 3 años y más ########################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset((EDAD >= 3 & EDAD <= 130)) %>%
                 #filter(ENT_PAIS_ASI %in% estados) %>%
                  group_by(CVE_ENT) %>%
                   summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Bases/Estado/04_Movilidad estudiantil/2020/Matriz de MEst a nivel estatal 2020.RData"))

rownames(Migrantes) <- estados
colnames(Migrantes) <- estados

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_ENT, Value, -rowname)%>%
                 filter(rowname == CVE_ENT) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                sna::diag.remove(remove.val = 0) %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "CVE_ENT") %>%
                   melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_ASI") %>%
                    mutate_at(vars(3), as.numeric) %>%
                     as_tibble() %>%
                      filter(CVE_ENT != ENT_PAIS_ASI) %>%
                       group_by(CVE_ENT) %>%
                        summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               sna::diag.remove(remove.val = 0) %>%
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_ENT") %>%
                  melt(., id.vars = "CVE_ENT", variable.name = "ENT_PAIS_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_ENT != ENT_PAIS_ASI) %>%
                      group_by(ENT_PAIS_ASI) %>%
                       summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                        rename("CVE_ENT" = "ENT_PAIS_ASI")

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ENT")) %>%
          left_join(., Residentes, by = c("CVE_ENT")) %>%
          left_join(., Inmigrantes, by = c("CVE_ENT")) %>%
          left_join(., Emigrantes, by = c("CVE_ENT")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2))*1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2))*1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, 
           file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Indicadores de MEst a nivel estatal 2020.xlsx"), 
           overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Estado/04_Movilidad estudiantil/2020/Indicadores de MEst a nivel estatal 2020.RData"))
Indicadores de movilidad estudiantil
Nivel estatal
Clave de la entidad Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001 1 421 198 1 348 472 409 195 1 393 5 139 −3 746 6 532 0.2 0.7 −0.5 −10 278
002 3 739 797 3 586 020 928 737 1 794 1 480 314 3 274 0.1 0.1 0.0 −2 960
003 793 424 756 761 206 978 1 067 247 820 1 314 0.3 0.1 0.2 −494
004 926 858 880 668 244 610 2 692 1 241 1 451 3 933 0.6 0.3 0.3 −2 482
005 3 137 032 2 974 979 795 408 5 127 8 555 −3 428 13 682 0.3 0.6 −0.2 −17 110
006 728 300 698 161 188 763 1 640 2 510 −870 4 150 0.5 0.7 −0.2 −5 020
007 5 524 506 5 182 887 1 515 892 6 334 4 535 1 799 10 869 0.2 0.2 0.1 −9 070
008 3 725 058 3 558 510 980 103 1 266 1 137 129 2 403 0.1 0.1 0.0 −2 274
009 9 159 393 8 891 226 2 106 242 71 779 360 266 −288 487 432 045 1.6 8.0 −6.4 −720 532
010 1 821 279 1 723 495 499 785 8 267 3 770 4 497 12 037 0.9 0.4 0.5 −7 540
011 6 144 449 5 825 265 1 570 500 14 891 6 939 7 952 21 830 0.5 0.2 0.3 −13 878
012 3 525 695 3 326 321 997 396 10 131 3 280 6 851 13 411 0.6 0.2 0.4 −6 560
013 3 075 237 2 939 604 827 461 23 068 17 682 5 386 40 750 1.5 1.2 0.4 −35 364
014 8 303 835 7 919 382 2 141 496 16 138 15 207 931 31 345 0.4 0.4 0.0 −30 414
015 16 943 627 16 213 422 4 078 161 359 013 91 905 267 108 450 918 4.3 1.1 3.2 −183 810
016 4 728 162 4 476 355 1 183 800 12 738 7 761 4 977 20 499 0.6 0.3 0.2 −15 522
017 1 961 694 1 878 497 488 434 15 166 5 850 9 316 21 016 1.6 0.6 1.0 −11 700
018 1 226 179 1 167 186 337 538 5 081 1 891 3 190 6 972 0.8 0.3 0.5 −3 782
019 5 768 781 5 508 078 1 415 469 11 728 7 575 4 153 19 303 0.4 0.3 0.1 −15 150
020 4 113 433 3 906 788 1 088 162 15 049 12 403 2 646 27 452 0.8 0.6 0.1 −24 806
021 6 567 595 6 222 339 1 804 663 12 856 56 088 −43 232 68 944 0.4 1.8 −1.4 −112 176
022 2 362 209 2 253 500 608 969 4 874 14 250 −9 376 19 124 0.4 1.2 −0.8 −28 500
023 1 852 929 1 765 783 455 126 2 356 1 581 775 3 937 0.3 0.2 0.1 −3 162
024 2 815 438 2 682 817 751 992 6 288 11 759 −5 471 18 047 0.5 0.9 −0.4 −23 518
025 2 986 880 2 846 488 814 325 2 138 2 373 −235 4 511 0.1 0.2 0.0 −4 746
026 2 924 652 2 798 802 742 324 2 401 1 662 739 4 063 0.2 0.1 0.1 −3 324
027 2 397 125 2 278 148 681 447 3 867 5 476 −1 609 9 343 0.3 0.5 −0.1 −10 952
028 3 518 497 3 363 567 871 278 4 203 9 730 −5 527 13 933 0.2 0.6 −0.3 −19 460
029 1 340 912 1 275 470 335 194 21 770 5 325 16 445 27 095 3.3 0.8 2.5 −10 650
030 8 046 861 7 699 502 1 957 584 30 436 10 191 20 245 40 627 0.8 0.3 0.5 −20 382
031 2 317 135 2 217 158 608 838 2 036 3 479 −1 443 5 515 0.2 0.3 −0.1 −6 958
032 1 617 384 1 527 247 447 515 6 355 2 655 3 700 9 010 0.8 0.3 0.5 −5 310
Fuente: Estimaciones del CONAPO.

Nivel municipal

Movilidad estudiantil

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.3ymas <- mydata %>%
              mutate(CVE_MUN_ASI = paste0(ENT_PAIS_ASI, MUN_ASI)) %>%
               mutate(ENT_PAIS_ASI = case_when(.$ENT_PAIS_ASI %in% estados ~.$ENT_PAIS_ASI,
                                               .$ENT_PAIS_ASI %nin% estados ~ "888", #Residencia en otro país
                                               .$ENT_PAIS_ASI %in% "997" ~ "997",
                                               .$ENT_PAIS_ASI %in% "998" ~ "998",
                                               .$ENT_PAIS_ASI %in% "997" ~ "999"),
                      CVE_MUN_ASI = case_when(.$CVE_MUN_ASI %in% municipios ~.$CVE_MUN_ASI,
                                              #### Se excluyen los municipios que no fueron muestreados
                                              .$CVE_MUN_ASI %in% municipios_nomuestra ~ "777",
                                               nchar(.$CVE_MUN_ASI) == 3 ~ "888",  #Asistencia escolar en otro país
                                              .$CVE_MUN_ASI %in% "997999" ~ '997999',
                                              .$ENT_PAIS_ASI %in% "997" ~ "997",
                                              .$ENT_PAIS_ASI %in% "998" ~ "998",
                                              .$ENT_PAIS_ASI %in% "999" ~ "999",
                                              .$MUN_ASI %in% "999" ~ "999")) %>%
                mutate(EDAD = as.numeric(.$EDAD)) %>%
                 subset(EDAD >= 3 & EDAD <= 130) %>%
                  select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_ASI, EDAD) %>%
                   filter(CVE_MUN_ASI %in% municipios) 

MC <- Pob.3ymas %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_municipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames 
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel municipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel municipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.estudiantil")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel municipal 2020.xlsx"), overwrite = TRUE)

Matriz de movilidad estudiantil a nivel municipal, 2020

Matriz de movilidad estudiantil
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 37 0 0 1366 122 101 12 0 240 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 13095 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 13315 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 4370 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 36 45 0 29323 121 88 0 0 11 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 11641 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 15896 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 2489 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 5605 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 3 0 0 431 233 196 0 0 5 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 266099 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 24958 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 19295 0 43 0 7 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 14139 31 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 75849 146 20 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 0 284 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 298 36 23 195 18 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 79728 0 38 37 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 64557 11 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 7948 14 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios) 

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE))

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                                tabla1[[i]] %>%
#                                 as.data.frame() %>%
#                                  adorn_totals(c("row", "col"), 
#                                                fill = "-", 
#                                                 na.rm = TRUE, 
#                                                  ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                    select(`Otros estados`) %>%
#                                     slice(nrow(.)) %>%
#                                      mutate(`Otros estados` = .$`Otros estados`/30) %>%
#                                       pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                   tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      adorn_totals(c("row", "col"), 
#                                                    fill = "-", 
#                                                     na.rm = TRUE, 
#                                                      ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                       slice(nrow(.)) %>%
#                                        mutate(Total = .$Total/50) %>%
#                                        pull(Total)
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio",  
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio",  
                                  Emigrantes = "%Entran por estudio")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst a nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel municipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- colorRampPalette(c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/ChordDiagram de MEst desagregado por estado.pdf"

## Gráficos a nivel municipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.1,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/Etiquetas a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 10, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Indicadores

Se realizan cálculos generales de movilidad:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • \(\%\) Inmigrantes

  • \(\%\) %Emigrante

  • Migración bruta

  • Migración Neta

  • \(\%\) Tasa de movilidad bruta

  • \(\%\) Tasa de movilidad neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Pob. estudiantil de 3 años y más ########################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <= 130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel municipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value ,-rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel municipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel municipal 2020.RData"))
Indicadores de movilidad estudiantil
Nivel municipal
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 3 139 16 133 −12 994 19 272 0.68 3.494 −2.8 −32 266
001002 51 474 48 275 13 095 1 173 493 680 1 666 4.70 1.977 2.7 −986
001003 58 155 55 019 13 315 567 119 448 686 2.00 0.421 1.6 −238
001004 16 997 15 959 4 370 516 209 307 725 6.26 2.537 3.7 −418
001005 129 859 122 544 29 323 7 830 1 915 5 915 9 745 12.41 3.035 9.4 −3 830
001006 47 557 44 893 11 641 1 630 1 084 546 2 714 7.05 4.690 2.4 −2 168
001007 57 269 53 484 15 896 990 2 295 −1 305 3 285 3.58 8.289 −4.7 −4 590
001008 9 552 8 868 2 489 196 118 78 314 4.26 2.562 1.7 −236
001009 22 461 21 182 5 605 644 35 609 679 5.90 0.321 5.6 −70
001010 20 382 18 987 5 129 193 465 −272 658 1.96 4.725 −2.8 −930
001011 61 986 57 999 14 930 3 075 1 061 2 014 4 136 10.25 3.537 6.7 −2 122
002001 440 624 422 238 112 987 638 857 −219 1 495 0.30 0.397 −0.1 −1 714
002002 1 042 395 1 004 592 266 099 596 870 −274 1 466 0.12 0.170 −0.1 −1 740
002003 102 896 98 206 24 958 1 260 2 136 −876 3 396 2.51 4.249 −1.7 −4 272
002004 1 910 568 1 829 472 459 410 4 038 3 468 570 7 506 0.43 0.371 0.1 −6 936
002005 126 264 121 701 27 084 2 092 1 401 691 3 493 3.37 2.260 1.1 −2 802
002006 117 050 109 811 28 950 0 0 0 0 0.00 0.000 0.0 0
003001 72 358 69 371 19 295 75 5 70 80 0.21 0.014 0.2 −10
003002 62 884 59 781 14 139 316 7 309 323 1.03 0.023 1.0 −14
003003 290 063 279 213 75 849 462 495 −33 957 0.32 0.348 0.0 −990
Fuente: Estimaciones del CONAPO.

Movilidad intramunicipal

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.3ymas <- mydata %>%
              mutate(CVE_MUN_ASI = paste0(ENT_PAIS_ASI, MUN_ASI)) %>%
               mutate(ENT_PAIS_ASI = case_when(.$ENT_PAIS_ASI %in% estados ~.$ENT_PAIS_ASI,
                                               .$ENT_PAIS_ASI %nin% estados ~ "888", #Residencia en otro país
                                               .$ENT_PAIS_ASI %in% "997" ~ "997",
                                               .$ENT_PAIS_ASI %in% "998" ~ "998",
                                               .$ENT_PAIS_ASI %in% "997" ~ "999"),
                      CVE_MUN_ASI = case_when(.$CVE_MUN_ASI %in% municipios ~.$CVE_MUN_ASI,
                                             #### Se excluyen los municipios que no fueron muestreados
                                              .$CVE_MUN_ASI %in% municipios_nomuestra ~ "777",
                                               nchar(.$CVE_MUN_ASI) == 3 ~ "888",  #Asistencia escolar en otro país
                                              .$CVE_MUN_ASI %in% "997999" ~ '997999',
                                              .$ENT_PAIS_ASI %in% "997" ~ "997",
                                              .$ENT_PAIS_ASI %in% "998" ~ "998",
                                              .$ENT_PAIS_ASI %in% "999" ~ "999",
                                              .$MUN_ASI %in% "999" ~ "999")) %>%
                mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_ASI & .$ENT_PAIS_ASI %in% estados ~ 1,
                                               .$CVE_ENT != .$ENT_PAIS_ASI & .$ENT_PAIS_ASI %in% estados ~ 2,
                                               .$ENT_PAIS_ASI %nin% estados ~ 3)) %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset(EDAD >= 3 & EDAD <= 130) %>%
                   select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_ASI, EDAD, I_Migracion) %>%
                    filter(CVE_MUN_ASI %in% municipios & I_Migracion == 1) 

MC <- Pob.3ymas %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_intramunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames 
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de movilidad estudiantil a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 37 0 0 1366 122 101 12 0 240 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 13095 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 13315 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 4370 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 36 45 0 29323 121 88 0 0 11 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 11641 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 15896 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 2489 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 5605 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 3 0 0 431 233 196 0 0 5 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 266099 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 24958 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19295 0 43 0 7 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 14139 31 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 75849 146 20 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 284 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 298 36 23 195 18 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 79728 0 38 37 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 64557 11 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 7948 14 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig)
#write.table(p, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = NULL,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = NULL,
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = NULL)

################################################################################
#tabla_municipios <- sapply(1:32, function(x)
#                                   tabla1[[x]] %>%
#                                     as.data.frame() %>%
#                                      adorn_totals(c("col"), 
#                                                    fill = "-", 
#                                                     na.rm = TRUE, 
#                                                      ,,,,contains(rownames(tabla1[[x]]))) %>%
#                                        select(Total) %>% 
#                                         summarise(mean = mean(Total)) %>%
#                                          pull(mean))

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
         tabla <- tabla1[[i]] %>%
                    as.data.frame() %>%
                     adorn_totals(c("row", "col"), 
                                   fill = "-", 
                                    na.rm = TRUE, 
              ,,,,contains(colnames(tabla1[[i]])))
                     
         addWorksheet(wb, paste(est[i]))
         writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
         saveWorkbook(wb, 
                      file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst nivel intramunicipal_Reduccion.xlsx"), 
                   overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio",  
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio",  
                                  Emigrantes = "%Entran por estudio")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intramunicipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- colorRampPalette(c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/ChordDiagram de MEst desagregado a nivel intramunicipal.pdf"

## Gráficos a nivel intramunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/Etiquetas a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
# Se utiliza el filtro de arriba
################################################################################

tabla1 <- lapply(1:32, function(x){
                   filtro  <- Inmigrantes %>%
                                full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                                  filter(value < filtro_mig[x]) %>% 
                                   pull(rn)
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ substr(.$rn, 1, 3)),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ substr(.$cn, 1, 3))) %>%

                     mutate(value = ifelse(.$rn != .$cn, .$value, 0)) %>%
                      filter(value > 0) 
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/04_Movilidad estudiantil/2020/GSankey de MEst desagregado a nivel intramunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de movilidad:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • \(\%\) Inmigrantes

  • \(\%\) %Emigrante

  • Migración bruta

  • Migración Neta

  • \(\%\) Tasa de movilidad bruta

  • \(\%\) Tasa de movilidad neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Pob. estudiantil de 3 años y más ########################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <= 130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intramunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value ,-rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otro demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel intramunicipal 2020.RData"))
Indicadores de movilidad estudiantil
Nivel intramunicipal
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 2 457 12 273 −9 816 14 730 0.532 2.658 −2.1 −24 546
001002 51 474 48 275 13 095 1 023 106 917 1 129 4.102 0.425 3.7 −212
001003 58 155 55 019 13 315 530 73 457 603 1.873 0.258 1.6 −146
001004 16 997 15 959 4 370 491 32 459 523 5.959 0.388 5.6 −64
001005 129 859 122 544 29 323 7 715 1 904 5 811 9 619 12.226 3.017 9.2 −3 808
001006 47 557 44 893 11 641 1 604 1 077 527 2 681 6.940 4.660 2.3 −2 154
001007 57 269 53 484 15 896 952 1 788 −836 2 740 3.438 6.458 −3.0 −3 576
001008 9 552 8 868 2 489 185 115 70 300 4.017 2.497 1.5 −230
001009 22 461 21 182 5 605 634 32 602 666 5.811 0.293 5.5 −64
001010 20 382 18 987 5 129 176 351 −175 527 1.788 3.566 −1.8 −702
001011 61 986 57 999 14 930 3 030 1 046 1 984 4 076 10.101 3.487 6.6 −2 092
002001 440 624 422 238 112 987 490 387 103 877 0.227 0.179 0.0 −774
002002 1 042 395 1 004 592 266 099 134 373 −239 507 0.026 0.073 0.0 −746
002003 102 896 98 206 24 958 1 194 2 133 −939 3 327 2.375 4.243 −1.9 −4 266
002004 1 910 568 1 829 472 459 410 3 632 3 248 384 6 880 0.388 0.347 0.0 −6 496
002005 126 264 121 701 27 084 2 092 1 401 691 3 493 3.375 2.260 1.1 −2 802
002006 117 050 109 811 28 950 0 0 0 0 0.000 0.000 0.0 0
003001 72 358 69 371 19 295 50 4 46 54 0.141 0.011 0.1 −8
003002 62 884 59 781 14 139 31 0 31 31 0.101 0.000 0.1 0
003003 290 063 279 213 75 849 166 366 −200 532 0.117 0.257 −0.1 −732
Fuente: Estimaciones del CONAPO.

Movilidad intermunicipal

Matrices

### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

#Clave de los municipios 2020 
municipios <- MUN %>%
               select(CVE_MUN) %>%
                unique() %>%
                 filter(CVE_MUN %nin% municipios_nomuestra) %>%
                  pull(CVE_MUN)

Pob.3ymas <- mydata %>%
              mutate(CVE_MUN_ASI = paste0(ENT_PAIS_ASI, MUN_ASI)) %>%
               mutate(ENT_PAIS_ASI = case_when(.$ENT_PAIS_ASI %in% estados ~.$ENT_PAIS_ASI,
                                               .$ENT_PAIS_ASI %nin% estados ~ "888", #Residencia en otro país
                                               .$ENT_PAIS_ASI %in% "997" ~ "997",
                                               .$ENT_PAIS_ASI %in% "998" ~ "998",
                                               .$ENT_PAIS_ASI %in% "997" ~ "999"),
                      CVE_MUN_ASI = case_when(.$CVE_MUN_ASI %in% municipios ~.$CVE_MUN_ASI,
                                             #### Se excluyen los municipios que no fueron muestreados
                                              .$CVE_MUN_ASI %in% municipios_nomuestra ~ "777",
                                               nchar(.$CVE_MUN_ASI) == 3 ~ "888",  #Asistencia escolar en otro país
                                              .$CVE_MUN_ASI %in% "997999" ~ '997999',
                                              .$ENT_PAIS_ASI %in% "997" ~ "997",
                                              .$ENT_PAIS_ASI %in% "998" ~ "998",
                                              .$ENT_PAIS_ASI %in% "999" ~ "999",
                                              .$MUN_ASI %in% "999" ~ "999")) %>%
                mutate(I_Migracion = case_when(.$CVE_ENT == .$ENT_PAIS_ASI & .$ENT_PAIS_ASI %in% estados ~ 1,
                                               .$CVE_ENT != .$ENT_PAIS_ASI & .$ENT_PAIS_ASI %in% estados ~ 2,
                                               .$ENT_PAIS_ASI %nin% estados ~ 3)) %>%
                 mutate(EDAD = as.numeric(.$EDAD)) %>%
                  subset(EDAD >= 3 & EDAD <= 130) %>%
                   select(FACTOR, ESTRATO, UPM, CVE_MUN, CVE_MUN_ASI, EDAD, I_Migracion) %>%
                    filter(CVE_MUN_ASI %in% municipios & I_Migracion == 2) 

MC <- Pob.3ymas %>%
       svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_intermunicipal.RDS"))
MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC) 

Se genera la matriz cuadrada y se le asignan los nombres de los estados.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 

rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 16)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames 
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de movilidad estudiantil a nivel municipal, 2020

Matriz de movilidad estudiantil
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 003001 003002 003003 003008 004001 004002 004003 004005 004006 004007 004009 004011 005002 005004
001001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004010 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
004011 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de los estados 
estado <- stringr::str_wrap(nom_estados, 100)

# Clave de los municipios 
### Municipios que no pertenecen en la muestra
municipios_nomuestra <- c("004012", "007125", "029048")

municipios <- MUN %>% 
               filter(CVE_MUN %nin% municipios_nomuestra) %>%
                mutate(municipios = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(municipios)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(municipios, Migrantes)

Emigrantes <- Emigrantes_function(municipios, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 0)

filtro_est <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   filter(value > 0)

### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>%
#### Filtro de estados filter(value > 100000000000 & rn != estados[x]) %>%
#### Se mete el filtro dentro de la función tabla1[[x]]
#p <- data.frame(estados = est,
 #               filtro_municipio = filtro_mig,
  #              filtro_estado = filtro_out)
#write.table(p, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intermunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/04_Movilidad estudiantil/2020/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
## Se generan los filtros correspondientes a la matriz cuadrada por estados 
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>% 
              filter(value > 0)

tabla1 <- migration_flows_municipality(tabla = tabla, 
                                       filtro_mun = filtro,
                                       filtro_est = filtro_est,
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group_mun = "Otros municipios",
                                       group_est = "Otros estados")

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:32, function(i){
#                                tabla1[[i]] %>%
#                                 as.data.frame() %>%
#                                  adorn_totals(c("row", "col"), 
#                                               fill = "-", 
#                                                na.rm = TRUE, 
#                                                 ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                   select(`Otros estados`) %>%
#                                    slice(nrow(.)) %>%
#                                     mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                      pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:32, function(i){
#                                  tabla1[[i]] %>%
#                                   as.data.frame() %>%
#                                    select(-c(`Otros estados`)) %>%
#                                     adorn_totals(c("row", "col"), 
#                                                   fill = "-", 
#                                                    na.rm = TRUE, 
#                                                     ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                      slice(nrow(.)) %>%
#                                       mutate(Total = .$Total/50) %>%
#                                        pull(Total)
#  })

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:32){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio",  
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio",  
                                  Emigrantes = "%Entran por estudio")

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:32){
     addWorksheet(wb, paste(est[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}

Dada la magnitud de municipios en algunos estados se seleccionan solo algunos de ellos.

tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Tabla MEst a nivel intermunicipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- colorRampPalette(c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A"))(50)

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/ChordDiagram de MEst desagregado a nivel intermunicipal.pdf"

## Gráficos a nivel intermunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text =c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/04_Movilidad estudiantil/2020/Etiquetas a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = nom_estados)

Gráfico Sankey

# Matriz cuadrada a nivel municipal 
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RData"))

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)

################################################################################
################################## Filtro ######################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                      filter(value > 0) %>%
                       group_by(rn) %>% 
                        summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (substr(.$rn, 1, 3) %in% estados | substr(.$cn, 1, 3) %in% estados), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 5000) %>% 
               pull(rn)
################################################################################

tabla1 <- lapply(1:32, function(x){
                   tabla %>%
                    mutate(rn = case_when(substr(.$rn, 1, 3) %in% estados[x] & .$rn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$rn, 1, 3) %in% estados[x]  & .$rn %nin% filtro ~ .$rn,
                                          substr(.$rn, 1, 3) %nin% estados[x] ~ substr(.$rn, 1, 3)),
                           cn = case_when(substr(.$cn, 1, 3) %in% estados[x] & .$cn %in% filtro ~ paste0("Otros municipios (", estados[x], ")"),
                                          substr(.$cn, 1, 3) %in% estados[x] & .$cn %nin% filtro ~ .$cn,
                                          substr(.$cn, 1, 3) %nin% estados[x] ~ substr(.$cn, 1, 3))) %>%

                     mutate(value = ifelse(.$rn != .$cn, .$value, 0)) %>%
                      filter(value > 0) 
  }
)
p <- lapply(1:32, function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                 geom_stratum(aes(fill = cn), 
                               color = "white", 
                                alpha = 0.65,  
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 7, family = "montserrat"),
                                   legend.position = c(1.02, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.5)) +
                        scale_fill_viridis_d(option = "A", end = 1, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/04_Movilidad estudiantil/2020/GSankey de MEst desagregado a nivel intermunicipal.pdf")
ggexport(list = p, width = 18, height = 10, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de movilidad:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • \(\%\) Inmigrantes

  • \(\%\) %Emigrante

  • Migración bruta

  • Migración Neta

  • \(\%\) Tasa de movilidad bruta

  • \(\%\) Tasa de movilidad neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura computacionalmente

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               filter(CVE_MUN %in% municipios) %>%
                group_by(CVE_MUN) %>%
                 summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Pob. estudiantil de 3 años y más ########################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <= 130) %>%
                 filter(CVE_MUN %in% municipios) %>%
                  group_by(CVE_MUN) %>%
                   summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value ,-rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otro demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>% 
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
            mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                   Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                   Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                   Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                   Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/04_Movilidad estudiantil/2020/Indicadores de movilidad estudiantil a nivel intermunicipal 2020.RData"))
Indicadores de movilidad estudiantil
Nivel intermunicipal
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 0 682 3 860 −3 178 4 542 0.148 0.8361 −0.7 −7 720
001002 51 474 48 275 0 150 387 −237 537 0.602 1.5519 −1.0 −774
001003 58 155 55 019 0 37 46 −9 83 0.131 0.1626 0.0 −92
001004 16 997 15 959 0 25 177 −152 202 0.303 2.1483 −1.8 −354
001005 129 859 122 544 0 115 11 104 126 0.182 0.0174 0.2 −22
001006 47 557 44 893 0 26 7 19 33 0.112 0.0303 0.1 −14
001007 57 269 53 484 0 38 507 −469 545 0.137 1.8311 −1.7 −1 014
001008 9 552 8 868 0 11 3 8 14 0.239 0.0651 0.2 −6
001009 22 461 21 182 0 10 3 7 13 0.092 0.0275 0.1 −6
001010 20 382 18 987 0 17 114 −97 131 0.173 1.1583 −1.0 −228
001011 61 986 57 999 0 45 15 30 60 0.150 0.0500 0.1 −30
002001 440 624 422 238 0 148 470 −322 618 0.069 0.2179 −0.1 −940
002002 1 042 395 1 004 592 0 462 497 −35 959 0.090 0.0971 0.0 −994
002003 102 896 98 206 0 66 3 63 69 0.131 0.0060 0.1 −6
002004 1 910 568 1 829 472 0 406 220 186 626 0.043 0.0235 0.0 −440
002005 126 264 121 701 0 0 0 0 0 0 0 0 0
002006 117 050 109 811 0 0 0 0 0 0 0 0 0
003001 72 358 69 371 0 25 1 24 26 0.071 0.0028 0.1 −2
003002 62 884 59 781 0 285 7 278 292 0.929 0.0228 0.9 −14
003003 290 063 279 213 0 296 129 167 425 0.208 0.0906 0.1 −258
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
mapview 2.11.0 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.